﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Common
{
	/// <summary>
	/// Helper methods for work with files
	/// </summary>
	public static class FileUtility
	{
		/// <summary>
		/// Check file attribute if it ReadOnly change it to normal
		/// </summary>
		/// <param name="fileName"></param>
		public static void MakeFileWritable(string fileName)
		{
			if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
				return;

			FileAttributes atts = File.GetAttributes(fileName);
			if ((atts & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
			{
				File.SetAttributes(fileName, FileAttributes.Normal);
			}
		}

		/// <summary>
		/// Clear file content set lenght to 0
		/// </summary>
		/// <param name="fileName"></param>
		public static void ClearFileContent(string fileName)
		{
			if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
				return;
			FileStream fs = null;
			try
			{
				fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.Write);
				if (fs.CanSeek)
					fs.Seek(0, SeekOrigin.Begin);

				fs.SetLength(0);
			}
			catch
			{ }
			finally
			{
				if (fs != null)
					fs.Dispose();
			}
		}
	}
}
